import PreloadConfig from "./PreloadConfig";
import GlobalData  from "./global";
import Util from "./Util";

export class Preloader {
    needLogin: boolean;
    private sprite: Laya.Sprite;
    private subcomp: boolean;//分包加载是否完成
    private preloadComp: boolean;
    private progressBar: Laya.ProgressBar;
    private loadComp: boolean;
    private config:PreloadConfig;
    constructor() {

    }

    public startToLoad(config:PreloadConfig): void {
        this.needLogin = config.login;
        this.config = config;
        this._start();
    }

    private onLoadFail(e):void {
        console.log('load error:' + e);
        this.onPreLoadComplete();
    }


    private _start():void {
        
        var r = [this.config.preloadBg,this.config.preloadBar];
        this.subcomp = false;
        var ldm: Laya.LoaderManager = Laya.loader.load(r, Laya.Handler.create(this, this.onPreLoadComplete));
        ldm.setGroup('', 'preloader');
        ldm.once(Laya.Event.ERROR, this, this.onLoadFail);
        GlobalData.instance.adapter.loadSubRes(this.config.subRes, Laya.Handler.create(this, this.onSubLoadComplete));
    };

    private onSubLoadComplete() {
        this.subcomp = true;
        this.toLoadRes();
    }


    private onPreLoadComplete() {
        this.preloadComp = true;
        this.toLoadRes();
        
    }

    private toLoadRes() {
        if (!this.subcomp || !this.preloadComp) {
            return;
        }

        //这里主要触发登录
        this.checkStart();
        this.loadComp = false;
        var sprite = new Laya.Sprite;
        sprite.name = "preload";
        Laya.stage.addChild(sprite);
        this.sprite = sprite;

        console.log(Laya.stage.width);
        console.log(Laya.stage.designWidth);
        console.log(Laya.stage.displayWidth);
        sprite.graphics.drawTexture(Laya.loader.getRes(this.config.preloadBg), 0, 0, Laya.stage.displayWidth, Laya.stage.displayHeight);

        var bar = new Laya.ProgressBar(this.config.preloadBar);
        bar.width = Util.getNumInRange(1000,400,Laya.stage.width-100);
        this.progressBar = bar;
        bar.x = Laya.stage.width / 2 - bar.width / 2;
        bar.y = Laya.stage.designHeight - 120;
        // bar.sizeGrid = "5,5,5,5";
        sprite.addChild(bar);
        if(this.config.showLayaPoweredby){
            let text:Laya.Label = new Laya.Label("Powered by LayaAir Engine");
            text.fontSize = 18;
            text.x = (Laya.stage.width - text.width)/2;
            text.y = Laya.stage.height-30;
            sprite.addChild(text);
        }
        var d2 = [
            {
                url: "res/atlas/home.atlas",
                type: Laya.Loader.ATLAS
            },
            {
                url: "res/atlas/images.atlas",
                type: Laya.Loader.ATLAS
            }, {
                url: "images/bg.png",
            }, {
                url: "res/prefabs.json",
                tupe: Laya.Loader.JSON
            }
            , {
                url: "res/atlas/joystick.atlas",
                type: Laya.Loader.ATLAS
            }
        ];
        Laya.loader.load(this.config.res2D, Laya.Handler.create(this, this.load3d), Laya.Handler.create(this, this.onLoadProgress));
    }

    //加载3D资源
    private load3d(all) {
        if (all) {
            //3D 资源在这里加载
            var d3 = [
                {
                    url: "models/robot/robot.lh",
                }
                , {
                    url: "models/map/map.lh",
                }

                , {
                    url: "models/gouzi/gouzi.lh",
                }
            ];
            if (this.config.res3D.length > 0) {
                Laya.loader.create(this.config.res3D, Laya.Handler.create(this, this.onLoadComplete), Laya.Handler.create(this, this.onLoadProgress));
            } else {
                this.onLoadComplete(true);
            }
        }
    }


    private onLoadComplete(all) {
        if (all) {
            this.progressBar.value = 1;
            //Laya.MiniAdpter && Laya.MiniAdpter.sendAtlasToOpenDataContext("res/atlas/toprank.atlas");
            if(Laya.MiniAdpter && this.config.sharedContextRes.length>0){
                this.config.sharedContextRes.forEach(element => {
                    Laya.MiniAdpter.sendAtlasToOpenDataContext(element);
                });
            }
            this.loadComp = true;
            this.checkStart();
        } else {
            console.log("load not comp");
        }
    }

    private onDown() {
        this.progressBar.destroy();
        Laya.loader.clearResByGroup("preloader");
        this.sprite.removeSelf();
    }
    private isActive() {
        return this.sprite.parent != null;
    }
    
    public destroy():void {
        this.onDown();
    }

    private onLoadProgress(e):void {
        console.log(e);
        this.progressBar.value += e;
    }


    private onLogin(uinfo):void {
        this.needLogin = false;
        GlobalData.instance.userData.setUinfo(uinfo);
        this.checkStart();
    }

    private checkStart():void {
        if (this.needLogin) {
            GlobalData.instance.adapter.login(Laya.Handler.create(this, this.onLogin));
            return;
        }
        if (!this.loadComp) {
            return;
        }
        GlobalData.instance.init_after_preload();
        this.config.callback && this.config.callback.run();
        this.destroy();
    }
}
